/**
 * 排序初始化
 */
function sortInit(url) {
    $(".th-sortable").on("click", function () {
        var order_type;
        if ($(this).hasClass("active")) {
            $(this).removeClass("active");
            order_type = "DESC";
        } else {
            $(this).addClass("active");
            order_type = "ASC";
        }
        location.href = url + "/" + $(this).data("name") + "/" + order_type;
    })
}

/**
 * 实现ajax登录
 * @param login_url
 * @param index_url
 */
function ajax_login(login_url, index_url) {
    $(function () {
        var username = $(".username").val();
        var password = $(".password").val();
        var captcha = $(".captcha input").val();
        var data = {
            "username": username,
            "password": password,
            "captcha": captcha
        };
        if (username == "") {
            crm.alert("请输入您的用户名", "error", function () {
            }, package_url("login/login/crm_login"));
        } else if (password == "") {
            crm.alert("请输入您的密码", "error", function () {
            }, package_url("login/login/crm_login"));
        } else {
            crm_ajax(data, login_url, function (res) {
                if (res.state == 0) {
                    crm.alert(res.msg, "error", function () {
                    }, package_url("login/login/crm_login"));
                    $(".confirm_login .password").val("");
                } else {
                    location.href = index_url;
                }
            });
        }
    })
}

/**
 * 退出登录
 * @param exit_url
 */
function exit(exit_url) {
    $(".exit_crm").on("click", function () {
        crm.alert("确认退出么?", "question", function () {
            crm_ajax({}, exit_url, function (res) {
                if (res) {
                    location.href = "/";
                }
            })
        }, true);
    })
}

/*
 * 验证图片
 * @param target      目标文件
 * @param res         返回结果
 */
function validate_img(target) {
    var res;
    if (!/image\/\w+/.test(target[0].type)) {
        res = {
            "status": false,
            "msg": "请传入有效图片"
        }

    } else if (target[0].size >= 5242880) {
        res = {
            "status": false,
            "msg": "上传图片要小于5M"
        };
    } else {
        res = {
            "status": true,
            "msg": "验证成功"
        };
    }
    return res;
}

/**
 * 上传图片
 * @param fileName
 * @param upload_url
 */
function uploadFile(fileName, upload_url) {
    var formData = new FormData();
    formData.append(fileName, $("#" + fileName)[0].files[0]);
    $.ajax({
        url: upload_url,
        type: 'POST',
        data: formData,
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        dataType: "json",
        success: function (responseStr) {
            if (responseStr.status === 1) {
                crm.alert(responseStr.msg, "success");
                $("#preview").attr('src', responseStr.img_path);
                $("#file_val").val(responseStr.img_path);
            } else {
                crm.alert(responseStr.msg, "error");
            }
        }
    });

}

/*
 * Ajax预处理请求
 * @param data             传输的数据
 * @param request_url      请求的地址
 * @param callback         返回结果所执行的函数
 */

function crm_ajax(data, request_url, callback, error_back_url) {
    callback = callback ? callback : function () {
    };
    $.ajax({
        url: request_url,
        type: "POST",
        async: false,
        dataType: "json",
        data: data,
        success: function (res) {
            if (res.code == 0) {
                crm.alert(res.msg, "error", function () {
                    error_back_url = error_back_url ? error_back_url : package_url("home/index/index");
                    location.href = error_back_url;
                });
            } else {
                callback(res);
            }
        }
    })
}

/*
 * 组装地址
 * @param order_url       目标地址
 * @param return          返回完整地址
 */
function package_url(order_url) {
    return "/" + order_url;
}

/*
 * 时间戳转日期(精确到秒)
 */
function get_date_time(target) {
    return new Date(parseInt(target) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}

/*
 * 日期(精确到秒)转时间戳
 */
function get_time(target) {
    var f = target.split(' ', 2);
    var d = (f[0] ? f[0] : '').split('-', 3);
    var t = (f[1] ? f[1] : '').split(':', 3);
    return (new Date(
            parseInt(d[0], 10) || null,
            (parseInt(d[1], 10) || 1) - 1,
            parseInt(d[2], 10) || null,
            parseInt(t[0], 10) || null,
            parseInt(t[1], 10) || null,
            parseInt(t[2], 10) || null
        )).getTime() / 1000;
}

/*
 *获取当前时间用"-"隔开
 * 格式是  2016-01-01 23:59:59
 * type(true精确到秒，false精确到天)
 */
function getNowTime(type) {
    var date = new Date();
    var seperator1 = "-"; //年月日分隔符
    var seperator2 = ":"; //时分秒分隔符
    var month = date.getMonth() + 1; //月份是0~11，要加1为当前月
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }

    if (type) {
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds();
    } else {
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
    }

    return currentdate;
}

/*
 * 消息窗口切换
 */
$(function () {
    $(".message_control1").on("mouseover", function () {
        $(".message_content1").css("display", "block");
        $(".message_content2").css("display", "none");
        $(".message_control1").css("background", "#fff");
        $(".message_control2").css("background", "#e1e1e1");
    });
    $(".message_control2").on("mouseover", function () {
        $(".message_content2").css("display", "block");
        $(".message_content1").css("display", "none");
        $(".message_control2").css("background", "#fff");
        $(".message_control1").css("background", "#e1e1e1");
    })

});

/*
 * 获取消息信息
 */
function get_message() {
    var audio = $("#audio")[0];
    audio.pause();
    crm_ajax("", package_url("consultant_module/message/get_message"), function (res) {
        var now_time = get_time(getNowTime()); //获取当前时间的时间戳
        var now_message = new Array();
        $(".message_content").html("");
        if (res.message_old.length > 0) {
            for (k in res.message_old) {
                $("<div class='message_content_box'><div class='message_content_top'><span class='message_date'>[" + get_date_time(res.message_old[k].last_date) + "]</span><span>(咨询者:" + res.message_old[k].consultant_name + ")</span><span>" + res.message_old[k].content + "</span></div></div>").appendTo(".message_content2");
            }
        } else {
        }
        if (res.message_future.length > 0) {
            for (k in res.message_future) {
                $("<div class='message_content_box'><div class='message_content_top'><span class='message_date'>[" + get_date_time(res.message_future[k].last_date) + "]</span><span>(咨询者:" + res.message_future[k].consultant_name + ")</span><span>" + res.message_future[k].content + "</span></div></div>").appendTo(".message_content1");
                if (res.message_future[k].last_date <= now_time + 30) {
                    now_message[k] = res.message_future[k];
                }
            }
        } else {
        }

        var len = now_message.length;
        k = len;
        if (len > 0) {
            digui();
        }

        function digui() {
            audio.play();
            k--;
            // k = k!==undefined?k:len - 1;
            data = {"id": now_message[k].id};
            var message_content_now = "(咨询者:" + now_message[k].consultant_name + ") " + now_message[k].content;

            if (k <= 0) {
                crm.alert(message_content_now, "info", function () {
                    change_message(data, k)
                }, false, function (dismiss) {
                    change_message(data, k);
                });
            } else {
                crm.alert(message_content_now, "info", function () {
                    change_message(data, k);
                }, false, function (dismiss) {
                    change_message(data, k);
                });
            }
        }

        function change_message(data, k) {
            crm_ajax(data, package_url("consultant_module/message/change_message_status"), function () {
                // digui.bind(null,--k);
                audio.pause();
                if (k == 0) {
                    get_message();
                } else {
                    digui();
                }
            });
        }

        $(".badge").text(res.message_future.length);
    });
}

/*
 * 饼图数据渲染
 * title_text  标题文本内容
 * order_title 提示框文本标题
 * show_data   数据(通过后台输出)
 */
function pie(title_text, order_title, show_data) {
    option = {
        title: {
            text: title_text,
            x: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series: [{
            name: order_title,
            type: 'pie',
            radius: '80%',
            center: ['50%', '50%'],
            data: show_data,
            itemStyle: {
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }]
    };
    return option;
}

/*
 * 曲线图数据渲染
 * title_text  标题文本内容
 * show_date_arr X轴显示内容数组
 * show_data   数据(通过后台输出)
 */
function line(title_text, show_date_arr, res_all_data) {
    option = {
        title: {
            text: title_text
        },
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: show_date_arr
        },
        yAxis: {
            type: 'value'
        },
        series: res_all_data
    };
    return option;
}

/*
 * 通用信息弹窗
 * title            弹窗标题
 * pre_popup_html   在富文本域之前的html结构
 * after_popup_html 在富文本域之后的html结构
 * callback         弹窗元素事件绑定
 */
function popup_window(title, pre_popup_html, after_popup_html, callback) {
    var run = true;//判断是否可以正常运行
    if (title == "" || typeof title != "string") {
        run = false
    }
    if (run) {
        var common_popup = $("#common_popup");
        var popup_web = $(".popup_web");
        var popup_rich_text = $(".popup_rich_text");
        var popup_content_html = "<i class='fa fa-times popup_exit'></i><div class='popup_top'><span></span></div>";
        popup_content_html += pre_popup_html;
        popup_rich_text.before($(popup_content_html));
        popup_rich_text.after($(after_popup_html));
        /*弹窗标题绑定*/
        $(".popup_top span").text(title);
        /*绑定弹窗关闭事件*/
        $(".popup_exit").on("click", function () {
            common_popup.fadeOut();
            popup_rich_text.siblings().remove();
            popup_rich_text.css("display", "none");
            $("#editor").removeClass();
            $("#editor").addClass("form-control rich_text");
            $("#editor").html("");
        })
        if (callback) {
            callback();
        }
        common_popup.fadeIn();
    } else {
        crm.alert("系统错误，请联系管理员", "error");
    }
}
